<template>
  <div class="tags">
    <el-tag
      v-for="(tag,index) in tags"
      :key="tag.name"
      :closable="tag.name!=='home'"
      :effect="route.name===tag.name ? 'dark':'plain'"
      @click="handleTag(tag)"
      @close="handleClose(tag, index)"
    >
      {{ tag.label }}
    </el-tag>
  </div>
</template>  

<script setup>
import { computed } from 'vue'
import { useAllDataStore } from '@/stores'
import { useRouter, useRoute } from 'vue-router'

const store = useAllDataStore()
const router = useRouter()
const route = useRoute()

// 从 store 中获取 tags 数据
const tags = computed(() => store.state.tags)

// 点击标签页跳转
const handleTag = (tag) => {
  store.selectMenu(tag)
  router.push(tag.path)
}

// 关闭标签页
const handleClose = (tag, index) => {
  // 如果关闭的不是当前页面，直接删除即可
  if(tag.name !== route.name) {
    store.undateMenu(tag)
    return
  }
  
  // 如果关闭的是当前页面，需要先确定跳转到哪个页面，再删除标签
  const tagsLength = tags.value.length
  
  // 如果关闭的是最后一个标签，跳转到前一个标签
  if(index === tagsLength - 1) {
    const targetTag = tags.value[index - 1]
    store.selectMenu(targetTag)
    router.push(targetTag.path)
  } else {
    // 如果关闭的不是最后一个标签，跳转到后一个标签
    const targetTag = tags.value[index + 1]
    store.selectMenu(targetTag)
    router.push(targetTag.path)
  }
  
  // 最后删除当前标签
  store.undateMenu(tag)
}
</script>

<style lang="less" scoped>
.tags {
  padding: 10px 20px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e6e6e6;
  
  .el-tag {
    margin-right: 10px;
    cursor: pointer;
    
    &:hover {
      opacity: 0.8;
    }
  }
}
</style>